<template>
  <div class="home-container">
    <!-- 头部区域 -->
    <van-nav-bar fixed>
      <!-- 左侧的插槽 -->
      <template #left>
        <img src="../../assets/toutiao_logo.png" alt="logo" class="logo" />
      </template>
      <!-- 右侧的插槽 -->
      <template #right>
        <van-icon name="search" color="white" size="18" @click="$router.push('/search')" />
      </template>
    </van-nav-bar>
    <!-- 标签栏 -->
    <!-- before-change 切换标签前的回调函数，返回 false 可阻止切换，支持返回 Promise -->
    <!-- change 当前激活的标签改变时触发 -->
    <van-tabs v-model="active" sticky offset-top="1.22666667rem" :before-change='beforeTabsChange' @change='onTabsChange'>
      <van-tab v-for="item in userChannel" :key="item.id" :title="item.name">
        <!-- 每一个标签下都有文章列表 -->
        <art-list :channel-id="item.id"></art-list>
      </van-tab>
    </van-tabs>
    <!-- 小加号 -->
    <van-icon name="plus" size="16" class="plus" @click="show = true" />
    <!-- 点击小加号弹出遮罩层 -->
    <van-popup v-model="show" :close-on-click-overlay='false' @closed="isDel = false">
     <div class="popup-container">

  <!-- 弹出层的头部区域 -->
  <van-nav-bar title="频道管理">
    <template #right>
      <van-icon name="cross" size="14" color="white" @click="show = false"/>
    </template>
  </van-nav-bar>

  <!-- 弹出层的主体区域 -->
  <div class="pop-body">
    <!-- 我的频道 -->
    <div class="my-channel-box">
      <div class="channel-title">
        <div>
          <span class="title-bold">已添加频道：</span>
          <span class="title-gray">{{isDel?'点击删除频道':'点击查看频道'}}</span>
        </div>
        <!-- 编辑按钮 -->
        <span class="btn-edit" @click="isDel=!isDel">{{isDel?'返回':'编辑'}}</span>
      </div>
      <!-- 我的频道列表 -->
      <van-row type="flex">
        <van-col span="6" v-for="(item,index) in userChannel" :key="item.id">
          <!-- 用户的频道 Item 项 -->
          <div @click="onUserChannelClick(item,index)" class="channel-item van-hairline--surround">{{item.name}}
               <!-- 删除的图标 -->
          <van-badge color="transparent" class="cross-badge" v-if="(isDel&&item.id!==0&&userChannel.length>2)">
        <template #content>
          <van-icon name="cross" class="badge-icon" color="#cfcfcf" size="12" />
        </template>
      </van-badge>

          </div>
        </van-col>
      </van-row>
    </div>

    <!-- 分隔线 -->
    <div class="van-hairline--top sp-line"></div>

    <!-- 更多频道 -->
    <div class="more-channel-box">
      <div class="channel-title">
        <div>
          <span class="title-bold">可添加频道：</span>
          <span class="title-gray">点击添加频道</span>
        </div>
      </div>
      <!-- 更多频道列表 -->
      <van-row type="flex">
        <van-col span="6" v-for="(item) in moreChannle" :key="item.id">
          <div class="channel-item van-hairline--surround"  @click="addChannel(item)">{{item.name}}</div>
        </van-col>
      </van-row>
    </div>
  </div>
</div>

    </van-popup>
  </div>
</template>

<script>
import { getUserChannelAPI, getAllChannelAPI, updateUserChannelAPI } from '../../API/homeAPI'
import ArtList from '../../components/ArtList'
// /用来储存索引和高度的关系
const indexToTop = {}

export default {
  name: 'Home',
  components: {
    ArtList
  },
  data () {
    return {
      active: 0,
      userChannel: [], // 用户的频道列表
      allChannel: [], // 获取到的所有频道列表
      show: false,
      isDel: false // 控制遮罩层
    }
  },
  methods: {
    async initUserChannel () {
      const { data: res } = await getUserChannelAPI()
      // console.log(res)
      if (res.message === 'OK') {
        this.userChannel = res.data.channels
        // console.log(this.userChannel)
      }
    },
    // 获取所有频道列表
    async initAllChannel () {
      const { data: res } = await getAllChannelAPI()
      // console.log(res)
      this.allChannel = res.data.channels
      // console.log(this.allchannel)
    },
    // 给我的频道添加内容
    addChannel (item) {
      this.userChannel.push(item)
      this.updataUserChannel()
      // const newArr = []
      // this.userChannel.forEach((item, index) => {
      //   newArr.push(
      //     {
      //       id: item.id,
      //       seq: index + 1
      //     }
      //   )
      // }).filter(item => item.id !== 0)
    },
    async  updataUserChannel () {
      const newArr = this.userChannel.filter(item => item.id !== 0).map((item, index) => ({
        id: item.id,
        seq: index
      }))

      const res = await updateUserChannelAPI(newArr)
      if (res.message === 'OK') {
        this.$notify({ type: 'success', message: '添加成功' })
      }
    },
    // 点击删除那一项
    onUserChannelClick (channel, index) {
      if (this.isDel) {
        if (channel.name === '推荐' || this.userChannel.length === 2) return

        // 在编辑状态下删除
        this.userChannel = this.userChannel.filter(item =>
          item.id !== channel.id
        )
        this.updataUserChannel()
        // console.log(item)
      } else {
        // 不删除的状态

        this.active = index
        this.show = false
      }
    },
    // 离开当前tab,点击另一个tab时触发
    beforeTabsChange () {
      // 没明白
      indexToTop[this.active] = window.scrollY
      console.log(indexToTop)
      return true
    },
    // 从一个tab离开,进入到要获取数据的tab的时候触发
    onTabsChange () {
      this.$nextTick(() => {
        window.scrollTo(0, indexToTop[this.active] || 0)
      })
    }
  },
  computed: {
    moreChannle () {
      const arr = []
      this.allChannel.forEach(item => {
        const index = this.userChannel.findIndex(x => {
          if (x.id === item.id) {
            return true
          }
        })

        if (index === -1) {
          arr.push(item)
        }
      })
      return arr
    }

  },
  created () {
    this.initUserChannel()
    this.initAllChannel()
  },
  activated () { // 只要切换到此组件就会触发
    // console.log(this.$route.meta.top)
    // 只要切换到此组件就会触发
    // scrollTo() 方法可把内容滚动到指定的坐标。
    // 第一个参数是 X轴位置 第二个是Y轴位置
    window.scrollTo(0, this.$route.meta.top)
  }
}
</script>

<style lang="less" scoped>
// 组件外层容器的样式
.home-container {
  padding-top: 46px;
  padding-bottom: 50px;
}
// logo 样式
.logo {
  height: 80%;
}
// 给标签栏右侧一个空间 放小加号
/deep/ .van-tabs__wrap {
  padding-right: 36px;
  background-color: white;
}
//  小加号样式
.plus {
  position: fixed;
  top: 58px;
  right: 10px;
  z-index: 999;
}
// 遮罩层样式
.van-popup,
.popup-container {
  background-color: transparent;
  height: 100%;
  width: 100%;
}

.popup-container {
  display: flex;
  flex-direction: column;
}

.pop-body {
  flex: 1;
  overflow: scroll;
  padding: 8px;
  background-color: white;
}

.my-channel-box,
.more-channel-box {
  .channel-title {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    line-height: 28px;
    padding: 0 6px;
    .title-bold {
      font-weight: bold;
    }
    .title-gray {
      color: gray;
      font-size: 12px;
    }
  }
}

.btn-edit {
  border: 1px solid #a3a2a2;
  padding: 0 10px;
  line-height: 20px;
  height: 20px;
  border-radius: 6px;
  font-size: 12px;
}

.channel-item {
  font-size: 12px;
  text-align: center;
  line-height: 36px;
  background-color: #fafafa;
  margin: 6px;
}

.cross-badge {
  position: absolute;
  right: -3px;
  top: 0;
  border: none;
}

.sp-line {
  margin: 10px 0 20px 0;
}
</style>
